import tkinter as tk
import serial
import time
import pyautogui
import threading
from threading import Timer


class RepeatingTimer(Timer):
    def run(self):
        while not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
            self.finished.wait(self.interval)


class UseTimer:
    def __init__(self, interval, function_name, *args, **kwargs):
        """
        :param interval:时间间隔
        :param function_name:可调用的对象
        :param args:args和kwargs作为function_name的参数
        """
        self.timer = RepeatingTimer(interval, function_name, *args, **kwargs)

    def timer_start(self):
        self.timer.start()

    def timer_cancle(self):
        self.timer.cancel()


class GUI:
    def __init__(self, root):
        self.text_on = None
        self.text_on_off = None
        self.T_start = None
        self.timter_rx = None
        self.T_com = None
        self.text_key = None
        self.button_stop = None
        self.button_start = None
        self.button_search = None
        self.text = None
        self.text_status = None
        self.ser = serial.Serial()
        self.KEYBOARD_COM = 'COM1'
        self.initGUI(root)


    def initGUI(self, root):
        grid_frame = tk.Frame(root)
        grid_frame.grid()

        root.title('keyBoard')
        root.geometry('500x150')
        self.text = tk.Label(root, text='宏定义按键', bg='green', font=('Arial', 12), width=30, height=2)
        self.text.grid(row=0, column=0)

        self.text_key = tk.Label(root, text='', bg='red', font=('Arial', 12), width=30, height=2)
        self.text_key.grid(row=0, column=1)

        self.text_status = tk.Label(root, text='未连接', bg='green', font=('Arial', 12), width=30, height=2)
        self.text_status.grid(row=1, column=1)

        self.text_on = tk.Label(root, text='运行状态', bg='green', font=('Arial', 12), width=30, height=2)
        self.text_on.grid(row=3, column=0)

        self.text_on_off = tk.Label(root, text='已停止', bg='red', font=('Arial', 12), width=30, height=2)
        self.text_on_off.grid(row=3, column=1)

        self.button_search = tk.Button(root, text="寻找设备", command=self.__com)
        self.button_search.grid(row=1, column=0)

        self.button_start = tk.Button(root, text=" 打开 ", command=self.__key_mian)
        self.button_start.grid(row=2, column=0)

        self.button_stop = tk.Button(root, text=" 关闭 ", command=self.__off)
        self.button_stop.grid(row=2, column=1)
        root.mainloop()

    def __com(self):
        i = 1
        while i < 255:  # 轮询COM口
            name = 'COM' + str(i)
            try:
                # print(f'尝试连接{name},', end='')
                self.ser = serial.Serial(name)
                self.ser.baudrate = 9600
                self.ser.timeout = 0.01  # 读超时设置
                time.sleep(3)
                self.ser.set_buffer_size(rx_size=1, tx_size=10)
                self.ser.write('1'.encode('utf-8'))  # 向端口写指令
                recv = self.ser.readline()
                if recv == b'keyboard\r\n':
                    self.KEYBOARD_COM = 'COM' + str(i)
                    self.text_status['text'] = f'已连接{self.KEYBOARD_COM}'
                    break

            except serial.serialutil.SerialException as e:
                i += 1
                pass
            continue

    def __key_mian(self):
        self.text_on_off['text'] = '正在运行'
        self.text_on_off['bg'] = 'green'
        self.timter_rx = UseTimer(0.1, self.rx_task)
        self.timter_rx.timer_start()

    def rx_task(self):
        rx_buf = self.ser.read(1)
        self.switch_case(self, rx_buf)

    def __off(self):
        self.text_on_off['text'] = '已停止运行'
        self.timter_rx.timer_cancle()

    @staticmethod
    def switch_case(self, argument):
        temp = argument
        temp = temp.decode('utf-8')
        self.text_key['text'] = f'按下{temp}'
        if argument == b'0':
            pyautogui.press('0')
        elif argument == b'1':
            pyautogui.press('1')
        elif argument == b'2':
            pyautogui.press('2')
        elif argument == b'3':
            pyautogui.press('3')
        elif argument == b'4':
            pyautogui.press('4')
        elif argument == b'5':
            pyautogui.press('5')
        elif argument == b'6':
            pyautogui.press('6')
        elif argument == b'7':
            pyautogui.press('7')
        elif argument == b'8':
            pyautogui.press('8')
        elif argument == b'9':
            pyautogui.press('9')
        elif argument == b'U':
            pyautogui.hotkey('win', 'shiftleft', 's')
        elif argument == b'D':  # 删除到行首
            pyautogui.hotkey('ctrlleft', 'altleft', 'shiftleft', 'o')
        elif argument == b'R':
            pyautogui.hotkey('ctrlleft', 'y')
        elif argument == b'L':
            pyautogui.hotkey('ctrlleft', 'z')
        elif argument == b'A':
            pyautogui.hotkey('ctrl', 'c')
        elif argument == b'B':
            pyautogui.hotkey('ctrl', 'v')
        else:
            pass


if __name__ == "__main__":
    win = tk.Tk()
    myGUI = GUI(win)
